package 锁.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 真正的多线程开发
 * 线程就是一个资源类，没有任何附属的操作
 */

public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        //Runnable接口为函数式接口
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"a").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"b").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"c").start();
    }
}

//资源类oop编程
class Ticket {
    //属性，方法
    private int number = 50;
    Lock lock = new ReentrantLock();

    //买票的方式
    public  void sale() {
        lock.lock();//加锁

        try {
            //业务代码
            if (number>0) {
                System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票,剩余："+number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}
